import tkinter as tk
from tkinter import ttk, messagebox

from utils import printer_util


class AddPrinterDialog(tk.Toplevel):
    def __init__(self, parent, config_manager, on_add_callback):
        super().__init__(parent)
        self.title("添加系统打印机")
        self.geometry("600x400")
        self.transient(parent)
        self.grab_set()

        self.config_manager = config_manager
        self.on_add_callback = on_add_callback

        self.setup_ui()
        self.load_system_printers()

    def setup_ui(self):
        main_frame = ttk.Frame(self, padding="10")
        main_frame.pack(fill=tk.BOTH, expand=True)

        ttk.Label(
            main_frame, text="从系统中选择要管理的打印机:", font=("Arial", 12)
        ).pack(pady=5, anchor=tk.W)

        # Treeview 显示打印机列表
        cols = ("name", "ip", "status")
        self.tree = ttk.Treeview(
            main_frame, columns=cols, show="headings", selectmode="extended"
        )

        self.tree.heading("name", text="打印机名称")
        self.tree.heading("ip", text="IP地址")
        self.tree.heading("status", text="状态")

        self.tree.column("name", width=250)
        self.tree.column("ip", width=120)
        self.tree.column("status", width=150)

        self.tree.pack(fill=tk.BOTH, expand=True, pady=5)

        # 按钮区域
        btn_frame = ttk.Frame(main_frame)
        btn_frame.pack(fill=tk.X, pady=10)

        ttk.Button(btn_frame, text="添加选中", command=self.add_selected).pack(
            side=tk.LEFT, padx=5
        )
        ttk.Button(btn_frame, text="刷新列表", command=self.load_system_printers).pack(
            side=tk.LEFT, padx=5
        )
        ttk.Button(btn_frame, text="关闭", command=self.destroy).pack(
            side=tk.RIGHT, padx=5
        )

    def load_system_printers(self):
        # 清空现有列表
        for i in self.tree.get_children():
            self.tree.delete(i)

        # 加载新数据
        printers = printer_util.get_system_printers()
        for p in printers:
            self.tree.insert("", "end", values=(p["name"], p["ip"], p["status"]))

    def add_selected(self):
        selected_items = self.tree.selection()
        if not selected_items:
            messagebox.showwarning("未选择", "请至少选择一台打印机进行添加。")
            return

        added_count = 0
        for item in selected_items:
            printer_data = self.tree.item(item, "values")
            name, ip, _ = printer_data
            self.config_manager.add_printer(name, ip)
            added_count += 1

        messagebox.showinfo("成功", f"成功添加 {added_count} 台打印机到配置。")
        self.on_add_callback()  # 通知主界面刷新
        self.destroy()
